"""
高性能表格模型 - 支持百万级数据虚拟滚动
"""
from typing import Any, Optional, List
from PySide6.QtCore import QAbstractTableModel, QModelIndex, Qt, Signal
from PySide6.QtGui import QColor
try:
    from .data_model import MetricsModel, TraceEvent
except ImportError:
    from data_model import MetricsModel, TraceEvent


class VirtualTableModel(QAbstractTableModel):
    """虚拟滚动表格模型 - 支持百万级trace事件"""
    
    data_updated = Signal()
    
    def __init__(self, metrics_model: MetricsModel, parent: Optional[object] = None):
        super().__init__(parent)
        self.metrics_model = metrics_model
        self._headers = ['时间戳', '事件类型', '线程ID', '进程ID', '持续时间(μs)', '元数据']
        self._visible_row_start = 0
        self._visible_row_count = 1000  # 初始可见行数
    
    def rowCount(self, parent: QModelIndex = QModelIndex()) -> int:
        """返回总行数"""
        if parent.isValid():
            return 0
        return self.metrics_model.events.size
    
    def columnCount(self, parent: QModelIndex = QModelIndex()) -> int:
        """返回列数"""
        if parent.isValid():
            return 0
        return len(self._headers)
    
    def data(self, index: QModelIndex, role: int = Qt.ItemDataRole.DisplayRole) -> Any:
        """获取单元格数据"""
        if not index.isValid():
            return None
        
        row = index.row()
        col = index.column()
        
        # 越界检查
        if row >= self.metrics_model.events.size:
            return None
        
        # 获取事件
        events_list = list(self.metrics_model.events.buffer)
        event = events_list[row]
        
        if role == Qt.ItemDataRole.DisplayRole:
            if col == 0:
                return f"{event.timestamp:.2f}"
            elif col == 1:
                return event.event_type
            elif col == 2:
                return str(event.thread_id)
            elif col == 3:
                return str(event.process_id)
            elif col == 4:
                return f"{event.duration:.2f}"
            elif col == 5:
                return str(event.metadata)
        
        elif role == Qt.ItemDataRole.BackgroundRole:
            # 交替行背景色
            if row % 2 == 0:
                return QColor(250, 250, 250)
            else:
                return QColor(255, 255, 255)
        
        elif role == Qt.ItemDataRole.TextAlignmentRole:
            if col in [0, 2, 3, 4]:  # 数值列居中
                return Qt.AlignmentFlag.AlignCenter
            return Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
        
        return None
    
    def headerData(self, section: int, orientation: Qt.Orientation, role: int = Qt.ItemDataRole.DisplayRole) -> Any:
        """获取表头数据"""
        if orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole:
            return self._headers[section]
        elif orientation == Qt.Orientation.Vertical and role == Qt.ItemDataRole.DisplayRole:
            return str(section + 1)
        return None
    
    def refresh(self) -> None:
        """刷新数据"""
        self.beginResetModel()
        self.endResetModel()
        self.data_updated.emit()
    
    def append_events(self, events: List[TraceEvent]) -> None:
        """追加事件（增量更新）"""
        if not events:
            return
        
        start_row = self.metrics_model.events.size
        end_row = start_row + len(events) - 1
        
        self.beginInsertRows(QModelIndex(), start_row, end_row)
        self.metrics_model.add_events_batch(events)
        self.endInsertRows()
        self.data_updated.emit()


class StatisticsModel(QAbstractTableModel):
    """统计信息表格模型"""
    
    def __init__(self, metrics_model: MetricsModel, parent: Optional[object] = None):
        super().__init__(parent)
        self.metrics_model = metrics_model
        self._headers = ['事件类型', '计数', '平均时长', '最小时长', '最大时长']
        self._data_cache: List[tuple] = []
    
    def rowCount(self, parent: QModelIndex = QModelIndex()) -> int:
        if parent.isValid():
            return 0
        return len(self._data_cache)
    
    def columnCount(self, parent: QModelIndex = QModelIndex()) -> int:
        if parent.isValid():
            return 0
        return len(self._headers)
    
    def data(self, index: QModelIndex, role: int = Qt.ItemDataRole.DisplayRole) -> Any:
        if not index.isValid():
            return None
        
        row = index.row()
        col = index.column()
        
        if row >= len(self._data_cache):
            return None
        
        row_data = self._data_cache[row]
        
        if role == Qt.ItemDataRole.DisplayRole:
            if col == 0:
                return row_data[0]  # 事件类型
            elif col == 1:
                return str(row_data[1])  # 计数
            elif col == 2:
                return f"{row_data[2]:.2f}"  # 平均时长
            elif col == 3:
                return f"{row_data[3]:.2f}"  # 最小时长
            elif col == 4:
                return f"{row_data[4]:.2f}"  # 最大时长
        
        elif role == Qt.ItemDataRole.TextAlignmentRole:
            return Qt.AlignmentFlag.AlignCenter
        
        return None
    
    def headerData(self, section: int, orientation: Qt.Orientation, role: int = Qt.ItemDataRole.DisplayRole) -> Any:
        if orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole:
            return self._headers[section]
        return None
    
    def refresh(self) -> None:
        """刷新统计数据"""
        self.beginResetModel()
        
        stats = self.metrics_model.get_statistics()
        self._data_cache.clear()
        
        for event_type, data in stats.items():
            self._data_cache.append((
                event_type,
                data['count'],
                data['avg_duration'],
                data['min_duration'],
                data['max_duration']
            ))
        
        self.endResetModel()
